package com.atxyj.srb.sms.controller.api;

import com.atxyj.common.exception.Assert;
import com.atxyj.common.result.R;
import com.atxyj.common.result.ResponseEnum;
import com.atxyj.common.util.RandomUtils;
import com.atxyj.common.util.RegexValidateUtils;
import com.atxyj.srb.sms.clent.CoreUserInfoClient;
import com.atxyj.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author: xyj
 * @date: 2021/7/31
 */
@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
//@CrossOrigin
@Slf4j
public class ApiSmsController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SmsService service;

    @Resource
    private CoreUserInfoClient coreUserInfoClient;

    @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号" , required = true) @PathVariable String mobile) {
        //验证手机号码不能为空
        Assert.notEmpty(mobile, ResponseEnum.CODE_NULL_ERROR);
        //是否是合法的手机号
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);

        //判断手机号是否以及注册
        boolean result = coreUserInfoClient.checkMobile(mobile);
        //断言这个手机号没被注册 如果被注册了 那么就返回手机号已被注册的信息
        Assert.isTrue( result == false , ResponseEnum.MOBILE_EXIST_ERROR);


        HashMap<String, Object> map = new HashMap<>();
        //生成四位数验证码的随机数
        String code = RandomUtils.getFourBitRandom();
        map.put("code", code);
        //service.send(mobile, SmsProperties.TEMPLATE_CODE, map);

        //将验证码存入redis
        redisTemplate.opsForValue().set("srb:sms:code"+ mobile , code, 5, TimeUnit.MINUTES);
        return R.ok().message("短信发送成功");
    }
}
